﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;

namespace Web_Blog.Controler
{
    public class Account
    {
        //Tạo account
        public static int CreateAccount(Object.CreateAccountObject acc)
        {
            ConnectDB.ConnectDB DB = new ConnectDB.ConnectDB();
            SqlConnection conn = DB.LayKetNoi();
            conn.Open();

            SqlCommand command = new SqlCommand("procTaoAcc", conn);
            command.CommandType = CommandType.StoredProcedure;

            command.Parameters.Add(new SqlParameter("@Nick",acc.Nick));
            command.Parameters.Add(new SqlParameter("@pass", acc.Pass));
            command.Parameters.Add(new SqlParameter("@name", acc.Name));
            command.Parameters.Add(new SqlParameter("@birth", acc.Birth));
            command.Parameters.Add(new SqlParameter("@sex", acc.Sex));
            command.Parameters.Add(new SqlParameter("@email", acc.Email));
            command.Parameters.Add(new SqlParameter("@phone", acc.Phone));
            command.Parameters.Add(new SqlParameter("@about", acc.About));

            int retval= command.ExecuteNonQuery();

            conn.Close();

            return retval;
        }

        //Hàm đăng nhập
        public static Object.LoginObject Login(Object.LoginObject login)
        {
            login.UID = -1;

            ConnectDB.ConnectDB DB = new ConnectDB.ConnectDB();
            SqlConnection conn = DB.LayKetNoi();
            conn.Open();

            SqlCommand command = new SqlCommand("procDangNhap", conn);
            command.CommandType = CommandType.StoredProcedure;

            command.Parameters.Add(new SqlParameter("@Nick", login.Username));
            command.Parameters.Add(new SqlParameter("@pass", login.Password));

            SqlDataReader reader = null;

            reader = command.ExecuteReader();

            if (reader.Read())
            {
                login.UID = int.Parse(reader["uID"].ToString());
                if (reader["avatar"] == null || reader["avatar"].ToString() == "")
                    login.Avatar = "";
                else
                    login.Avatar = reader["avatar"].ToString();

                //Nếu block là 1 thì đã bị khóa tài khoản
                if (reader["block"] != null && reader["block"].ToString() == "1")
                    login.UID = -2;
            }

            conn.Close();

            return login;
        }

        //Lấy profile user
        public static Object.UserProfileObject LoadProfile(int uID)
        {
            Object.UserProfileObject up = new Object.UserProfileObject();

            ConnectDB.ConnectDB DB = new ConnectDB.ConnectDB();
            SqlConnection conn = DB.LayKetNoi();
            conn.Open();

            SqlCommand command2 = new SqlCommand("procLayUser", conn);
            command2.CommandType = CommandType.StoredProcedure;
            command2.Parameters.Add(new SqlParameter("@uID", uID));
            SqlDataReader reader2 = null;
            reader2 = command2.ExecuteReader();
            if (reader2.Read())
            {
                up.About=reader2["about"].ToString();
                up.Avatar=reader2["avatar"].ToString();
                up.Birth=reader2["birth"].ToString();
                up.Createdate=reader2["createdate"].ToString();
                up.Email=reader2["email"].ToString();
                up.Name=reader2["name"].ToString();
                up.Nick=reader2["nick"].ToString();
                up.Phone=reader2["phone"].ToString();
                up.Setting=reader2["setting"].ToString();
                up.Sex=int.Parse(reader2["sex"].ToString());
                up.UID=int.Parse(reader2["uID"].ToString());
                up.Url=reader2["url"].ToString();
            }
            reader2.Close();

            conn.Close();
            return up;
        }

        //Sửa profile
        public static int UpdateProfile(Object.UserProfileObject acc)
        {
            ConnectDB.ConnectDB DB = new ConnectDB.ConnectDB();
            SqlConnection conn = DB.LayKetNoi();
            conn.Open();

            SqlCommand command = new SqlCommand("procSuaUser", conn);
            command.CommandType = CommandType.StoredProcedure;

            command.Parameters.Add(new SqlParameter("@uID2", acc.UID));
            command.Parameters.Add(new SqlParameter("@name2", acc.Name));
            command.Parameters.Add(new SqlParameter("@birth2", acc.Birth));
            command.Parameters.Add(new SqlParameter("@sex2", acc.Sex));
            command.Parameters.Add(new SqlParameter("@email2", acc.Email));
            command.Parameters.Add(new SqlParameter("@phone2", acc.Phone));
            command.Parameters.Add(new SqlParameter("@about2", acc.About));
            command.Parameters.Add(new SqlParameter("@avatar2", acc.Avatar));
            command.Parameters.Add(new SqlParameter("@setting2", acc.Setting));
            command.Parameters.Add(new SqlParameter("@url2", acc.Url));

            int retval = command.ExecuteNonQuery();
            
            conn.Close();

            return retval;
        }

        //Update avatar
        public static bool UpdateAvatar(HttpPostedFile myFile,string path)
        {
            int nFileLen = myFile.ContentLength;
            if (nFileLen == 0)
            {
                return false;
            }

            if (System.IO.Path.GetExtension(myFile.FileName).ToLower() != ".jpg")
            {
                return false;
            }

            byte[] myData = new Byte[nFileLen];
            myFile.InputStream.Read(myData,0,nFileLen);

            System.IO.FileStream newFile
                    = new System.IO.FileStream(path+".jpg", 
                                                System.IO.FileMode.Create);
            newFile.Write(myData,0, myData.Length);
            newFile.Close();
            return true;
            }

        //Đổi mật khẩu
        public static int ChangePassword(Object.ChangePasswordObject pass)
        {
            ConnectDB.ConnectDB DB = new ConnectDB.ConnectDB();
            SqlConnection conn = DB.LayKetNoi();
            conn.Open();

            SqlCommand command = new SqlCommand("procDoiMatKhau", conn);
            command.CommandType = CommandType.StoredProcedure;

            command.Parameters.Add(new SqlParameter("@uID", pass.UID));
            command.Parameters.Add(new SqlParameter("@oldpass",pass.Oldpass));
            command.Parameters.Add(new SqlParameter("@newpass", pass.Newpass));

            int retval= command.ExecuteNonQuery();

            conn.Close();
            return retval;
        }

        //Seach thành viên
        public static string SearchUser(string keyword)
        {
            int count = -1;
            string retval = "<tr>";

            ConnectDB.ConnectDB DB = new ConnectDB.ConnectDB();
            SqlConnection conn = DB.LayKetNoi();
            conn.Open();

            SqlCommand command = new SqlCommand("procTimThanhVien", conn);
            command.CommandType = CommandType.StoredProcedure;
            command.Parameters.Add(new SqlParameter("@key", keyword));
            SqlDataReader reader = command.ExecuteReader();

            while (reader.Read())
            {
                count++;                                        //Biến đếm để biết xuống dòng
                if ((count % 4) == 0) retval += "</tr><tr>";
                retval += "<td class=\"style6\" height=\"140\">  <a href=\"";
                retval += "TrangChu.aspx?u=" + reader["uID"].ToString();   //Đường dẫn link
                retval += "\"> <img src=\"";
                retval += Controler.Other.ParseAvatar(reader["avatar"].ToString());
                retval += "\" style=\"width:125px;height:125px\" /><br />";
                retval += reader["name"].ToString();
                retval += "</a> </td>";
            }
            conn.Close();
            retval += "</tr>";                                  //Đóng dòng cuối cùng
            retval = retval.Replace("<tr></tr>", "");
            return retval;
        }

        //==============================Dành cho admin panel

        //Hàm đăng nhập admin
        public static Object.LoginObject LoginAdmin(Object.LoginObject login)
        {
            login.UID = -1;

            ConnectDB.ConnectDB DB = new ConnectDB.ConnectDB();
            SqlConnection conn = DB.LayKetNoi();
            conn.Open();

            SqlCommand command = new SqlCommand("procDangNhapAdmin", conn);
            command.CommandType = CommandType.StoredProcedure;

            command.Parameters.Add(new SqlParameter("@Nick", login.Username));
            command.Parameters.Add(new SqlParameter("@pass", login.Password));

            SqlDataReader reader = null;

            reader = command.ExecuteReader();

            if (reader.Read())
            {
                login.UID = int.Parse(reader["uID"].ToString());
            }

            conn.Close();

            return login;
        }

        //Seach thành viên admin ra danh sách ID
        public static string SearchUserIDAdmin(string keyword)
        {
            string retval = "";

            ConnectDB.ConnectDB DB = new ConnectDB.ConnectDB();
            SqlConnection conn = DB.LayKetNoi();
            conn.Open();

            SqlCommand command = new SqlCommand("procTimThanhVien", conn);
            command.CommandType = CommandType.StoredProcedure;
            command.Parameters.Add(new SqlParameter("@key", keyword));
            SqlDataReader reader = command.ExecuteReader();

            while (reader.Read())
            {
                retval += ";" + reader["uID"].ToString() + ";";
            }
            conn.Close();
            return retval;
        }

        //Seach thành viên cho danh sách admin
        public static string SearchUserAdmin(string keyword)
        {
            string retval = "";

            ConnectDB.ConnectDB DB = new ConnectDB.ConnectDB();
            SqlConnection conn = DB.LayKetNoi();
            conn.Open();

            SqlCommand command = new SqlCommand("procTimThanhVien", conn);
            command.CommandType = CommandType.StoredProcedure;
            command.Parameters.Add(new SqlParameter("@key", keyword));
            SqlDataReader reader = command.ExecuteReader();

            retval += "<tr>";
            retval += "<td>User ID</td>";
            retval += "<td>Nickname</td>";
            retval += "<td>Tên</td>";
            retval += "<td>Ngày gia nhập</td>";
            retval += "<td>Trạng thái</td>";
            retval += "<td>Reset</td>";
            retval += "<td>Nhóm</td>";
            retval += "</tr>";

            while (reader.Read())
            {
                retval += "<tr>";
                retval += "<td>" + reader["uID"].ToString() + "</td>";
                retval += "<td>" + reader["nick"].ToString() + "</td>";
                retval += "<td>" + reader["name"].ToString() + "</td>";
                retval += "<td>" + reader["createdate"].ToString() + "</td>";
                retval += "<td><a href=\"./Khoa.aspx?u=" + reader["uID"].ToString()+"\">"+(reader["block"].ToString() == "1" ? "Khóa" : "Mở") + "</a></td>";
                retval += "<td><a href=\"./ResetTK.aspx?u=" + reader["uID"].ToString() + "\">Reset Pass</a></td>";
                retval += "<td><a href=\"./PhanQuyenTK.aspx?u=" + reader["uID"].ToString() + "\">"+Controler.Account.GetGroupName(int.Parse(reader["groupid"].ToString()!=""?reader["groupid"].ToString():"3"))+"</a></td>";
                retval += "</tr>";
            }
            conn.Close();
            return retval;
        }

        //Hàm khóa, mở khóa tài khoản
        public static int BlockAccount(int uID, int block)
        {
            ConnectDB.ConnectDB DB = new ConnectDB.ConnectDB();
            SqlConnection conn = DB.LayKetNoi();
            conn.Open();

            SqlCommand command = new SqlCommand("procBlockTaiKhoan", conn);
            command.CommandType = CommandType.StoredProcedure;
            command.Parameters.Add(new SqlParameter("@uID", uID));
            command.Parameters.Add(new SqlParameter("@bloc", block));
            int retval = command.ExecuteNonQuery();

            conn.Close();

            return retval;
        }

        //Hàm reset pass cho user
        public static int ResetPassword(int uID, string newpass)
        {
            ConnectDB.ConnectDB DB = new ConnectDB.ConnectDB();
            SqlConnection conn = DB.LayKetNoi();
            conn.Open();

            SqlCommand command = new SqlCommand("procResetPass", conn);
            command.CommandType = CommandType.StoredProcedure;
            command.Parameters.Add(new SqlParameter("@uID", uID));
            command.Parameters.Add(new SqlParameter("@pass", newpass));
            int retval = command.ExecuteNonQuery();

            conn.Close();

            return retval;
        }

        //Hàm phân quyền
        public static int ChangeGroup(int uID, int group)
        {
            ConnectDB.ConnectDB DB = new ConnectDB.ConnectDB();
            SqlConnection conn = DB.LayKetNoi();
            conn.Open();

            SqlCommand command = new SqlCommand("procPhanQuyen", conn);
            command.CommandType = CommandType.StoredProcedure;
            command.Parameters.Add(new SqlParameter("@uID", uID));
            command.Parameters.Add(new SqlParameter("@group", group));
            int retval = command.ExecuteNonQuery();

            conn.Close();

            return retval;
        }

        //Hàm lấy tên nhóm
        public static string GetGroupName(int gID)
        {
            string retval = "Users";

            ConnectDB.ConnectDB DB = new ConnectDB.ConnectDB();
            SqlConnection conn = DB.LayKetNoi();
            conn.Open();

            SqlCommand command = new SqlCommand("procLayNhom", conn);
            command.CommandType = CommandType.StoredProcedure;
            command.Parameters.Add(new SqlParameter("@groupid", gID));

            SqlDataReader rs = command.ExecuteReader();

            if (rs.Read())
                retval = rs["GroupName"].ToString();

            conn.Close();

            return retval;
        }
    }
}